<template>
  <a-space>
    <a-button @click="backhome">返回首页</a-button>
    <a-button v-if="timer" @click="back" type="primary">返回上一页({{ second }}s)</a-button>
    <a-button v-else @click="back" type="primary">返回上一页</a-button>
  </a-space>
</template>
<script>
import { setStore, getStoreStr, removeStore } from '../../../utils/storage/session'
const KEY = 'ERRORCOUNT'
export default {
  name: 'ErrorBackBtn',
  data() {
    return {
      timer: undefined,
      second: 9
    }
  },
  methods: {
    backhome() {
      this.clears()
      this.$router.replace('/')
    },
    back() {
      this.clears()
      this.$router.back()
    },
    //清空倒计时
    clears() {
      if (this.timer) clearInterval(this.timer)
      else removeStore(KEY)
    }
  },
  mounted() {
    //倒计时返回只能2次，第3的次就不再自动返回了
    let count = Number(getStoreStr(KEY) || 1)
    if (count <= 2) {
      this.timer = setInterval(() => {
        this.second--
        if (this.second <= 1) this.back()
      }, 1000)
    }
    count++
    setStore(KEY, count.toString())
  },
  //销毁解除绑定
  beforeDestroy() {
    this.clears()
  }
}
</script>
